<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2025-06-21 14:02:08
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-06-23 12:51:46
 * @Description: 
 * 
 * Copyright (c) 2025 by xiaoMing.Cao, All Rights Reserved. 
-->

<template>
  <div class="api-logs">
    <div class="api-logs-head">
      <el-form :inline="true" :model="data.form" class="demo-form-inline">
        <el-form-item label="日期">
          <el-date-picker v-model="data.form.date" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="路径">
          <el-input v-model="data.form.path" placeholder="请输入API路径" />
        </el-form-item>
        <el-form-item label="方法">
          <el-select v-model="data.form.method" placeholder="请选择请求方法">
            <el-option label="全部" value="" />
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="success" @click="exportData">实时统计</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 概览统计卡片 -->
    <div class="api-logs-overview">
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in overviewData" :key="index" @click="selectedCardClick(index)">
          <el-card :shadow="selectedCard === index ? 'always' : 'hover'" class="overview-card">
            <div class="overview-title">{{ item.date }}</div>
            <div class="overview-content">
              <div class="overview-item cursor-pointer" @click.stop="logDetail(item, 'all')">
                <div class="item-label">总请求数</div>
                <div class="item-value">{{ item.totalSuccess + item.totalFail + item.totalSlow }}</div>
              </div>
              <div class="overview-item cursor-pointer" @click.stop="logDetail(item, 'success')">
                <div class="item-label">成功请求</div>
                <div class="item-value success">{{ item.totalSuccess }}</div>
              </div>
              <div class="overview-item cursor-pointer" @click.stop="logDetail(item, 'fail')">
                <div class="item-label">失败请求</div>
                <div class="item-value error">{{ item.totalFail }}</div>
              </div>
              <div class="overview-item cursor-pointer" @click.stop="logDetail(item, 'slow')">
                <div class="item-label">慢请求</div>
                <div class="item-value warning">{{ item.totalSlow }}</div>
              </div>
              <div class="overview-item">
                <div class="item-label">失败率</div>
                <div class="item-value">{{ item.failRate }}%</div>
              </div>
              <div class="overview-item">
                <div class="item-label">慢请求率</div>
                <div class="item-value">{{ item.slowRate }}%</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- API统计表格 -->
    <div class="api-logs-main">
      <el-table :data="data.list" style="width: 100%" v-loading="loading">
        <el-table-column prop="path" label="API路径" min-width="250" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="100" align="center" />
        <el-table-column prop="success_count" label="成功请求数" width="120" align="center" />
        <el-table-column prop="fail_count" label="失败请求数" width="120" align="center" />
        <el-table-column prop="slow_count" label="慢请求数" width="120" align="center" />
        <el-table-column label="失败率" width="100" align="center">
          <template #default="scope">
            <span>{{ ((scope.row.fail_count / (scope.row.success_count + scope.row.fail_count)) * 100).toFixed(2) }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="avg_duration" label="平均耗时(ms)" width="120" align="center" />
        <el-table-column prop="max_duration" label="最大耗时(ms)" width="120" align="center" />
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewFailLogs(scope.row)" v-if="scope.row.fail_count > 0">查看失败</el-button>
            <el-button type="warning" size="small" @click="viewSlowLogs(scope.row)" v-if="scope.row.slow_count > 0">查看慢请求</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top: 15px" :page-size="parament.limit" @current-change="pageChange" background layout="prev, pager, next" :total="data.total" />
    </div>
  </div>
</template>

<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { getApiStats, getApiStatsOverview, triggerApiLogProcessing } from '@/api/apiLogs';
  import { ElMessage } from 'element-plus';

  // 添加组件名称，用于keep-alive
  defineOptions({
    name: 'ApiLogs'
  });

  const router = useRouter();
  const loading = ref(false);
  const overviewData = ref([]);

  // 所选哪一个卡片
  const selectedCard = ref(null);

  const data = reactive({
    list: [],
    total: 0,
    form: {
      date: '',
      path: '',
      method: '',
      status: 'all'
    }
  });

  const parament = reactive({
    page: 0,
    limit: 20,
    sort: 'path'
  });

  // 获取API统计数据
  const getList = () => {
    loading.value = true;
    console.log(data.form.date);
    getApiStats({ ...data.form, ...parament })
      .then(res => {
        if (res.code === 200) {
          data.list = res.data?.data || [];
          data.total = res.data?.total || 0;
        } else {
          ElMessage.error(res.message || '获取数据失败');
        }
      })
      .catch(err => {
        console.error('获取API统计数据失败', err);
        ElMessage.error('获取API统计数据失败');
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 获取概览数据
  const getOverviewData = () => {
    getApiStatsOverview()
      .then(res => {
        if (res.code === 200) {
          let resData = res.data || [];
          // 把数据倒序
          resData = resData.reverse();
          overviewData.value = resData;
          selectedCard.value = 0;
          data.form.date = resData[selectedCard.value]?.date;
          getList();
        } else {
          ElMessage.error(res.message || '获取概览数据失败');
        }
      })
      .catch(err => {
        console.error('获取API概览数据失败', err);
        ElMessage.error('获取API概览数据失败');
      });
  };

  // 选择哪个卡片
  const selectedCardClick = index => {
    selectedCard.value = index;
    data.form.date = overviewData.value[selectedCard.value]?.date;
    data.form.status = 'all';
    parament.page = 0;
    data.form.path = '';
    data.form.method = '';
    getList();
  };

  // 查看失败日志
  const viewFailLogs = row => {
    router.push({
      path: '/api-logs/fail',
      query: {
        path: row.path,
        method: row.method,
        date: data.form.date
      }
    });
  };

  // 查看慢请求日志
  const viewSlowLogs = row => {
    router.push({
      path: '/api-logs/slow',
      query: {
        path: row.path,
        method: row.method,
        date: data.form.date
      }
    });
  };

  const submitForm = () => {
    parament.page = 0;
    getList();
  };

  const resetForm = () => {
    data.form = {
      date: '',
      path: '',
      method: ''
    };
    getList();
  };

  const pageChange = page => {
    parament.page = page - 1;
    getList();
  };

  // 实时统计
  const exportData = () => {
    triggerApiLogProcessing().then(res => {
      if (res.code === 200) {
        ElMessage.success('实时统计成功');
        // 刷新概览数据
        getOverviewData();
      } else {
        ElMessage.error(res.message || '实时统计失败');
      }
    });
  };

  // 日志详情
  const logDetail = (item, status) => {
    data.form.date = item.date;
    if (status == 'success') {
      data.form.status = 'success';
    } else if (status == 'fail') {
      data.form.status = 'fail';
    } else if (status == 'slow') {
      data.form.status = 'slow';
    }
    // 当前选中的卡片
    selectedCard.value = overviewData.value.findIndex(item => item.date === data.form.date);
    getList();
  };

  onMounted(() => {
    getOverviewData();
  });
</script>

<style scoped lang="scss">
  .api-logs {
    padding: 15px;
    width: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .api-logs-head,
    .api-logs-main,
    .api-logs-overview {
      background-color: #fff;
      display: flex;
      padding: 15px;
      box-sizing: border-box;
      width: 100%;
      margin-bottom: 15px;
      flex-direction: column;
    }

    .api-logs-overview {
      .overview-card {
        margin-bottom: 15px;

        .overview-title {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 10px;
          color: #303133;
        }

        .overview-content {
          display: flex;
          flex-wrap: wrap;

          .overview-item {
            width: 50%;
            margin-bottom: 10px;

            .item-label {
              font-size: 12px;
              color: #909399;
            }

            .item-value {
              font-size: 16px;
              font-weight: bold;
              color: #303133;

              &.success {
                color: #67c23a;
              }

              &.error {
                color: #f56c6c;
              }

              &.warning {
                color: #e6a23c;
              }
            }
          }
        }
      }
    }
  }

  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }

  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }

  .el-table__header {
    background-color: #d3e3fd;
  }

  .cursor-pointer {
    cursor: pointer;
  }
</style>
